<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\Course;
use plugin\admin\app\model\CourseCategory;
use plugin\admin\app\model\CourseFile;
use plugin\admin\app\model\Text;

class CourseService
{
    public static function list($page = 0, $length = 10)
    {
        $offset = ($page - 1) * $length;

        $totalCount = Course::count();
        $list = Course::offset($offset)->limit($length)->get()->toArray();

        $categoryIds = array_column($list, 'category_id');
        $categories = CourseCategory::whereIn('id', $categoryIds)->get()->pluck('name', 'id')->toArray();

        foreach ($list as $key=>$item) {
            $item = json_decode(json_encode($item), true);
            $item['thumb'] = full_url($item['thumb']);
            $item['audio'] = full_url($item['audio']);
            $item['video'] = full_url($item['video']);
            $item['content'] = str_replace('src="', 'src="' . getenv('APP_URL'), $item['content']);
            $item['category_name'] = $categories[$item['category_id'] ?? 0] ?? '';
            $list[$key] = $item;
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function detail($id)
    {
        $course = Course::where('id', $id)->first();

        $course['thumb'] = full_url($course['thumb']);
        $course['audio'] = full_url($course['audio']);
        $course['video'] = full_url($course['video']);
        $course['content'] = str_replace('src="', 'src="' . getenv('APP_URL'), $course['content']);
        $category = CourseCategory::where('id', $course['category_id'])->first();

        $files = CourseFile::where('course_id', $id)->get()->toArray();
        $course['files'] = $files;
        $course['category_name'] = $category['name'] ?? '';

        return $course;
    }
}